<template>
  <div class="version-management">
    <div class="header">
      <h2>应用版本管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加版本
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-area">
      <el-select v-model="filterPlatform" placeholder="选择平台" @change="loadVersionList" clearable>
        <el-option label="Android" value="android" />
        <el-option label="iOS" value="ios" />
      </el-select>
    </div>

    <!-- 版本列表 -->
    <el-table
        :data="versionList"
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
    >
      <el-table-column prop="platform" label="平台" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.platform === 'android' ? 'success' : 'primary'">
            {{ scope.row.platform === 'android' ? 'Android' : 'iOS' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="versionName" label="版本号" width="100" />

      <el-table-column prop="versionCode" label="版本码" width="80" sortable />

      <el-table-column prop="description" label="版本描述" min-width="80">
        <template #default="scope">
          <el-tooltip :content="scope.row.description" placement="top">
            <span class="description-text">{{ scope.row.description }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="updateContent" label="更新内容" min-width="120">
        <template #default="scope">
          <div class="update-content">
            <pre>{{ scope.row.updateContent }}</pre>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="fileSize" label="文件大小" width="100">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>

      <el-table-column prop="updateType" label="更新类型" width="120">
        <template #default="scope">
          <el-tag :type="'success'">
            {{ scope.row.updateType }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="priority" label="优先级" width="150">
        <template #default="scope">
          <el-rate v-model="scope.row.priority" :max="5" size="small" disabled />
        </template>
      </el-table-column>

      <el-table-column label="下载方式" width="150">
        <template #default="scope">
          <div class="download-methods">
            <el-tag v-if="scope.row.playStoreUrl" size="small" type="success">Play商店</el-tag>
            <el-tag v-if="scope.row.downloadUrl" size="small" type="info">直接下载</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="isEnabled" label="启用状态" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.isEnabled"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="releaseTime" label="发布时间" width="150">
        <template #default="scope">
          {{ formatDateTime(scope.row.releaseTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editVersion(scope.row)">编辑</el-button>
          <el-button size="small" @click="copyDownloadLink(scope.row)">复制链接</el-button>
          <el-button size="small" type="danger" @click="deleteVersion(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @close="resetForm"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="平台" prop="platform">
          <el-select v-model="formData.platform" placeholder="请选择平台">
            <el-option label="Android" value="android" />
            <el-option label="iOS" value="ios" />
          </el-select>
        </el-form-item>

        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="formData.versionName" placeholder="如: 1.2.0" />
        </el-form-item>

        <el-form-item label="版本号" prop="versionCode">
          <el-input-number v-model="formData.versionCode" :min="1" placeholder="如: 120" />
        </el-form-item>

        <el-form-item label="版本描述" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="2"
              placeholder="请输入版本描述"
          />
        </el-form-item>

        <el-form-item label="更新内容" prop="updateContent">
          <el-input
              v-model="formData.updateContent"
              type="textarea"
              :rows="4"
              placeholder="请输入更新内容，每行一个功能点"
          />
        </el-form-item>

        <el-form-item label="更新类型" prop="updateType">
          <el-select v-model="formData.updateType" placeholder="请选择更新类型">
            <el-option label="推荐更新" value="RECOMMENDED" />
            <el-option label="可选更新" value="OPTIONAL" />
            <el-option label="仅通知" value="NOTIFY_ONLY" />
          </el-select>
          <div class="form-tip">
            推荐更新：显示对话框；可选更新：显示提示；仅通知：仅记录日志
          </div>
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-rate v-model="formData.priority" :max="5" />
          <span style="margin-left: 10px; color: #999;">1-5级，5为最高优先级</span>
        </el-form-item>

        <el-form-item label="Play商店链接" prop="playStoreUrl">
          <el-input v-model="formData.playStoreUrl" placeholder="Google Play商店下载链接（推荐）" />
        </el-form-item>

        <el-form-item label="直接下载地址" prop="downloadUrl">
          <div class="upload-section">
            <el-input v-model="formData.downloadUrl" placeholder="APK直接下载地址（备用）" />
            <el-upload
                class="upload-demo"
                :action="baseBackURL + '/upload/apk'"
                :show-file-list="false"
                :on-success="handleFileUpload"
                :before-upload="beforeFileUpload"
                accept=".apk,.ipa"
            >
              <el-button type="primary" style="margin-left: 10px">上传APK</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="文件大小" prop="fileSize">
          <el-input-number v-model="formData.fileSize" :min="0" placeholder="字节数" />
          <span style="margin-left: 10px; color: #999;">
            {{ formatFileSize(formData.fileSize) }}
          </span>
        </el-form-item>

        <el-form-item label="MD5校验" prop="md5">
          <el-input v-model="formData.md5" placeholder="文件MD5值（可选）" />
        </el-form-item>

        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
              v-model="formData.releaseTime"
              type="datetime"
              placeholder="选择发布时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="启用状态">
          <el-switch v-model="formData.isEnabled" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { versionApi } from '../api/version'
import {baseBackURL} from "@/utils/request.js";

// 响应式数据
const loading = ref(false)
const versionList = ref([])
const filterPlatform = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('添加版本')
const formRef = ref()

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  platform: 'android',
  versionName: '',
  versionCode: null,
  description: '',
  updateContent: '',
  downloadUrl: '',
  playStoreUrl: '',
  fileSize: null,
  md5: '',
  updateType: 'RECOMMENDED',
  priority: 3,
  releaseTime: '',
  isEnabled: true
})

// 表单验证规则
const formRules = {
  platform: [
    { required: true, message: '请选择平台', trigger: 'change' }
  ],
  versionName: [
    { required: true, message: '请输入版本名称', trigger: 'blur' }
  ],
  versionCode: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入版本描述', trigger: 'blur' }
  ]
}


// 生命周期
onMounted(() => {
  loadVersionList()
})

// 加载版本列表
const loadVersionList = async () => {
  loading.value = true
  try {
    const response = await versionApi.getVersionList(
        pagination.current,
        pagination.size,
        filterPlatform.value
    )
    if (response.code == 200) {
      versionList.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加版本'
  resetFormData()
  dialogVisible.value = true
}

// 编辑版本
const editVersion = (row) => {
  dialogTitle.value = '编辑版本'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除版本
const deleteVersion = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个版本吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await versionApi.deleteVersion(row.id)
    if (response.code == 200) {
      ElMessage.success('删除成功')
      loadVersionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    const response = await versionApi.updateVersion(row.id, row)
    if (response.code == 200) {
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.isEnabled = !row.isEnabled // 回滚状态
  }
}

// 复制下载链接
const copyDownloadLink = async (row) => {
  try {
    await navigator.clipboard.writeText(row.downloadUrl)
    ElMessage.success('下载链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 文件上传前验证
const beforeFileUpload = (file) => {
  const isValidType = file.type === 'application/vnd.android.package-archive' ||
      file.name.endsWith('.apk') ||
      file.name.endsWith('.ipa')

  if (!isValidType) {
    ElMessage.error('只能上传 APK 或 IPA 文件!')
    return false
  }

  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isLt100M) {
    ElMessage.error('文件大小不能超过 100MB!')
    return false
  }

  return true
}

// 文件上传成功
const handleFileUpload = (response) => {
  if (response.code == 200) {
    formData.downloadUrl = response.data.url
    formData.fileSize = response.data.fileSize
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

// 表格排序变更
const handleSortChange = (sortInfo) => {
  // 实现排序逻辑
  console.log('排序变更:', sortInfo)
}

// 分页大小变更
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadVersionList()
}

// 当前页变更
const handleCurrentChange = (current) => {
  pagination.current = current
  loadVersionList()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    let response
    if (formData.id) {
      response = await versionApi.updateVersion(formData.id, formData)
    } else {
      response = await versionApi.addVersion(formData)
    }

    if (response.code == 200) {
      ElMessage.success(formData.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadVersionList()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    platform: 'android',
    versionName: '',
    versionCode: null,
    description: '',
    updateContent: '',
    downloadUrl: '',
    fileSize: null,
    md5: '',
    minSupportVersion: '',
    releaseTime: '',
    forceUpdate: false,
    isEnabled: true
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style scoped>
.version-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.filter-area {
  margin-bottom: 20px;
}

.description-text {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.update-content {
  max-height: 100px;
  overflow-y: auto;
}

.update-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.4;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.upload-section {
  display: flex;
  align-items: center;
  width: 100%;
}

.upload-section .el-input {
  flex: 1;
}

.download-methods {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>